// pages/register/register.js
const { getCenterList, addWxUser } = require('../../utils/api.js');
const { getTownData, validateFields } = require('../../utils/tool.js');
const rules = {
  userName: '请输入用户名',
  password: '请输入密码',
  roleCode: '请选择角色',
  nickName: '请输入名称',
  town: '请选择街道',
  address: '请输入详细地址',
};

Page({
  /**
   * 组件的初始数据
   */
  data: {
    userName: '', // 用户名
    password: '', // 密码
    roleCode: 'wx_user', // wx_user、wx_company、wx_wuye、wx_town、wx_carTrans
    nickName: '', // 名称
    town: '', // 乡镇
    address: '', // 详细地址
    center: '', // 处理中心
    centerName: '',
    showPopup: false,
    showCenterPopup: false,
    columns: getTownData(),
    centerList: [],
  },

  handlePickerClick() {
    this.setData({ showPopup: true });
  },

  handleCenterPickerClick() {
    this.setData({ showCenterPopup: true });
  },

  onConfirm(e) {
    const { value } = e.detail;
    this.setData({
      town: value,
      showPopup: false,
    });
    if (this.data.roleCode == 'wx_town') {
      this.getCenterList(value);
    }
  },

  onCenterConfirm(e) {
    const { value } = e.detail;
    this.setData({
      center: value.id,
      centerName: value.name,
      showCenterPopup: false,
    });
  },

  onCancel() {
    this.setData({ showPopup: false, showCenterPopup: false });
  },

  onRadioChange(e) {
    this.setData({ roleCode: e.detail });
    if (this.data.town) {
      this.getCenterList(this.data.town);
    }
  },

  getCenterList(townName) {
    getCenterList({ townName }).then((res) => {
      this.setData({
        centerList: res.data || [],
      });
    });
  },

  infoinput(e) {
    const { flag } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({ [flag]: value });
  },

  handleSubmit() {
    const params = {
      userName: this.data.userName, // 用户名
      password: this.data.password, // 密码
      roleCode: this.data.roleCode, // wx_user、wx_company、wx_wuye、wx_town
      nickName: this.data.nickName, // 名称
      province: '江苏省', // 省
      city: '连云港市', // 市
      county: '东海县', // 区县
      town: this.data.town, // 乡镇
      address: this.data.address, // 详细地址
      center: this.data.center, // 处理中心
    };
    if (!validateFields(params, rules)) {
      return;
    }

    addWxUser(params).then(() => {
      wx.showToast({ title: '注册成功', icon: 'success' });
      wx.navigateBack();
    });
  },
});
